package com.xique.system.service.biz.service.impl;

import com.xique.common.core.constant.UserConstants;
import com.xique.common.core.domain.R;
import com.xique.common.core.utils.OrikaUtil;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.sys.api.domain.SysUser;
import com.xique.system.api.dto.SystemUserDTO;
import com.xique.system.api.model.LoginSystemUser;
import com.xique.system.bean.domain.*;
import com.xique.system.bean.search.ParkInfoSearch;
import com.xique.system.bean.search.SystemUserRsaSearch;
import com.xique.system.constants.SystemConstants;
import com.xique.system.service.biz.service.ISystemUserBizService;
import com.xique.system.service.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author shd
 * @create 2021/11/11 15:14
 */
@Service
public class SystemUserBizServiceImpl implements ISystemUserBizService {

    @Autowired
    private ISystemUserService systemUserService;

    @Autowired
    private ISystemUserRsaService systemUserRsaService;

    @Autowired
    private ISystemPermissionService systemPermissionService;

    @Autowired
    private ISystemDeptService systemDeptService;

    @Autowired
    private ISystemRoleService roleService;

    @Autowired
    private IParkInfoService parkInfoService;

    @Override
    public R<LoginSystemUser> getSystemUserByUserName(String userName) {

        SystemUser systemUser = systemUserService.selectUserByUserName(userName);

        if (StringUtils.isNull(systemUser)) {
            return R.fail("用户名或密码错误");
        }

        if (StringUtils.isNotNull(systemUser.getParkId())) {
            ParkInfo parkInfo = parkInfoService.selectParkInfoById(systemUser.getParkId());
            if (null != parkInfo) {
                systemUser.setParkName(parkInfo.getName());
            }
        }

//        if (StringUtils.isNotNull(systemUser.getParkCode())) {
//            ParkInfoSearch parkInfoSearch = new ParkInfoSearch();
//            parkInfoSearch.setCode(systemUser.getParkCode());
//            ParkInfo parkInfo = parkInfoService.selectParkInfoBySearch(parkInfoSearch);
//            if (null != parkInfo) {
//                systemUser.setParkId(parkInfo.getId());
//                systemUser.setParkName(parkInfo.getName());
//            }
//        }

        //TODO 添加角色集合和权限集合
        // 角色集合
        Set<String> roles = systemPermissionService.getRolePermission(systemUser.getUserId());
        // 权限集合
        Set<String> permissions = systemPermissionService.getMenuPermission(systemUser.getUserId());

        LoginSystemUser loginSystemUser = new LoginSystemUser();
        SystemUserDTO systemUserDTO = OrikaUtil.convert(systemUser, SystemUserDTO.class);
        if (systemUser.getDeptId()!= null && "01".equals(systemUser.getUserType())){
            //用户的类型为1（服务商），并且服务商id不为空，查询服务商logo信息
            SystemDept systemDept = systemDeptService.selectDeptById(systemUser.getDeptId());
            systemUserDTO.setLogo(systemDept.getLogo());
        }
        loginSystemUser.setSystemUser(systemUserDTO);
        loginSystemUser.setRoles(roles);
        loginSystemUser.setPermissions(permissions);

        return R.ok(loginSystemUser);
    }

    @Override
    public R<LoginSystemUser> getSystemUserByUserNameV1(String userName, String password) {

        SystemUser systemUser = systemUserService.selectUserByUserName(userName);

        if (StringUtils.isNull(systemUser)) {
            return R.fail("用户名或密码错误");
        }

        if (StringUtils.isNotNull(systemUser.getParkCode())) {
            ParkInfoSearch parkInfoSearch = new ParkInfoSearch();
            parkInfoSearch.setCode(systemUser.getParkCode());
            ParkInfo parkInfo = parkInfoService.selectParkInfoBySearch(parkInfoSearch);
            if (null != parkInfo) {
                systemUser.setParkId(parkInfo.getId());
            }
        }

        if (StringUtils.isNotNull(systemUser.getParkId())) {
            ParkInfo parkInfo = parkInfoService.selectParkInfoById(systemUser.getParkId());
            if (null != parkInfo) {
                systemUser.setParkName(parkInfo.getName());
            }
        }

        SystemUser update = new SystemUser();
        update.setUserId(systemUser.getUserId());
        update.setPassword(SecurityUtils.encryptPassword(password));
        systemUserService.updateById(update);

        systemUser.setPassword(update.getPassword());

        //TODO 添加角色集合和权限集合
        // 角色集合
        Set<String> roles = systemPermissionService.getRolePermission(systemUser.getUserId());
        // 权限集合
        Set<String> permissions = systemPermissionService.getMenuPermission(systemUser.getUserId());

        LoginSystemUser loginSystemUser = new LoginSystemUser();
        loginSystemUser.setSystemUser(OrikaUtil.convert(systemUser, SystemUserDTO.class));
        loginSystemUser.setRoles(roles);
        loginSystemUser.setPermissions(permissions);

        return R.ok(loginSystemUser);
    }

    @Override
    public AjaxResult getInfo() {
        Long userId = SecurityUtils.getUserId();
        SystemUser user = systemUserService.selectSystemUserById(userId);
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("未找到对应用户信息");
        }
        // 角色集合
        Set<String> roles = systemPermissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = systemPermissionService.getMenuPermission(userId);
        Long parkId = null == user.getParkId() ? SecurityUtils.getParkId() : user.getParkId();
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(parkId)) {
            ParkInfo parkInfo = parkInfoService.selectParkInfoById(parkId);
            ajax.put("park", parkInfo);
        }
        Long deptId = user.getDeptId();
        if (StringUtils.isNotNull(deptId)) {
            SystemDept dept = systemDeptService.selectDeptById(deptId);
            user.setDept(dept);
        }
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    @Override
    public AjaxResult getInfo(Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SystemRole role = new SystemRole();
        if (!SecurityUtils.isAdmin(userId)) {
//            if (UserConstants.Platform.ADMIN.equals(SecurityUtils.getPlatformType())) {
//                role.setRoleType(UserConstants.UserType.MANAGER);
//            }
            if (UserConstants.Platform.ADMIN_SERVICE.equals(SecurityUtils.getPlatformType())) {
                role.setRoleType(UserConstants.UserType.SERVICE_MANAGER);
            }
            if (UserConstants.Platform.ADMIN_PROJECT.equals(SecurityUtils.getPlatformType())) {
                role.setRoleType(UserConstants.UserType.PROJECT_MANAGER);
                role.setParkId(SecurityUtils.getParkId());
            }
        }
        List<SystemRole> roles = roleService.selectRoleListV1(role);
//        List<SystemRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if (StringUtils.isNotNull(userId))
        {
            SystemUser user = systemUserService.selectSystemUserById(userId);
            if (StringUtils.isNotNull(user.getDeptId())) {
                SystemDept dept = systemDeptService.selectDeptById(user.getDeptId());
                user.setDeptName(dept.getDeptName());
                user.setDept(dept);
            }
            ajax.put(AjaxResult.DATA_TAG, user);
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    @Override
    public R<String> getSystemUserKeyByUserName(String userName) {

        SystemUserRsaSearch search = new SystemUserRsaSearch();
        search.setUserName(userName);
        SystemUserRsa rsa = systemUserRsaService.selectSystemUserRsaBySearch(search);

        if (StringUtils.isNull(rsa)) {
            return R.fail("获取密码解析错误");
        }

        return R.ok(rsa.getPrivateKey());
    }

    @Override
    public R<List<SystemUserDTO>> selectRoleSystemUserList(Long userId) {
        List<SystemRole> roleList = roleService.selectRolesByUserId(userId);

        roleList = roleList.stream().filter(SystemRole::isFlag).collect(Collectors.toList());

        List<SystemUser> userList = systemUserService.selectUserListByRoleId(roleList.get(0).getRoleId());

        List<SystemUserDTO> dtos = OrikaUtil.converts(userList, SystemUserDTO.class);

        return R.ok(dtos);
    }
}
